/*
 * @Author: your name
 * @Date: 2021-08-26 10:46:31
 * @LastEditTime: 2021-09-22 20:01:13
 * @LastEditors: RongWei
 * @Description: In User Settings Edit
 * @FilePath: /maycur-business/tools/lib/buildAndPublish.js
 */
const simpleGit = require('simple-git');
const exec = require("exec-sh").promise;

const git = simpleGit({
    baseDir: process.cwd(),
    binary: 'git',
    maxConcurrentProcesses: 6
});
/**
 * 
 * @param {string} param0.tag: 发布的tag
 * @param {string} param0.version: prelease 升级预发布号，3.1.1-12 => 3.1.1-13; prepatch 升级修订号，3.1.1-12 => 3.1.2-0
 * @param {string} param0.commitmsg:发布需要提交git commit的message
 * @param {function} build 
 */
async function buildAndPublish(build, packageSrc, { tag, version = 'prerelease', commitmsg }) {
    // npm version 执行前会检查工作目录是否干净，-f 可跳过此步骤
    // 变更版本号后会写入 package.json 和 package-lock.json，自动进行提交和打标签操作，--no-git-tag-version 可禁止 tag 操作
    if (version === 'prerelease') {
        await exec('npm --no-git-tag-version version prerelease -f');
    } else {
        await exec('npm --no-git-tag-version version prepatch -f');
    }

    build().then(async () => {
        if (tag) {
            await exec(`npm publish ${packageSrc} --tag ${tag}`);
        } else {
            await exec(`npm publish ${packageSrc}`);
        }

        git.add('./*')
            .commit(commitmsg || `chore: publish package ${tag}`)
            .push();
    });
}

module.exports = buildAndPublish;